package pl.org.lutra.planner.gui.table;

import java.awt.Component;
import java.awt.event.MouseEvent;
import java.util.EventObject;

import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.text.JTextComponent;

import pl.org.lutra.planner.Planner;
import pl.org.lutra.planner.gui.table.DiveTableModel.DiveColumn;
import pl.org.lutra.planner.gui.util.DepthFormat;
import pl.org.lutra.planner.gui.util.TimeFormat;
import pl.org.lutra.planner.model.data.DiveSegment;
import pl.org.lutra.planner.model.input.Input;

public class DiveTable extends PlannerTable<DiveSegment> {
	private static final long serialVersionUID = 6706652465924456195L;

	private Input input = Planner.getInstance().getInput();

	public DiveTable() {
		super(new DiveTableModel());

		setRowSelectionAllowed(true);
		setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

		initColumnsBehavior();
	}

	private void initColumnsBehavior() {
		PaddingTableCellRenderer depthRenderer = new PaddingTableCellRenderer(new DepthFormat());
		setColumnBehavior(DiveColumn.START_DEPTH, depthRenderer, null);
		setColumnBehavior(DiveColumn.TARGET_DEPTH, depthRenderer,
				new FloatTableCellEditor(input.getDepthDocumentFilter()));

		PaddingTableCellRenderer timeRenderer = new PaddingTableCellRenderer(new TimeFormat());
		FloatTableCellEditor timeEditor = new FloatTableCellEditor(input.getTimeDocumentFilter());

		setColumnBehavior(DiveColumn.TIME, timeRenderer, timeEditor);
		setColumnBehavior(DiveColumn.RUNTIME, timeRenderer, timeEditor);
	}

	@Override
	public DiveTableModel getModel() {
		return (DiveTableModel) super.getModel();
	}

	public void selectRow(int index) {
		getSelectionModel().setSelectionInterval(index, index);
	}

	@Override
	public boolean editCellAt(int row, int column, EventObject e) {
		boolean result = super.editCellAt(row, column, e);

		selectCellContent(e);

		return result;
	}

	private void selectCellContent(EventObject e) {
		final Component editor = getEditorComponent();

		if ((editor == null) || !(editor instanceof JTextComponent)) {
			return;
		}

		if ((e != null) && (e instanceof MouseEvent)) {
			SwingUtilities.invokeLater(new Runnable() {
				@Override
				public void run() {
					((JTextComponent) editor).selectAll();
				}
			});
		} else {
			((JTextComponent) editor).selectAll();
		}
	}
}
